package cn.hwua.web;

import cn.hwua.dao.FoodDao;
import cn.hwua.dao.impl.FoodDaoImpl;
import cn.hwua.entity.Food;
import cn.hwua.util.StringUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/food/*")
public class FoodServlet extends HttpServlet {
    private FoodDao dao=new FoodDaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String baseURL = req.getContextPath();//获取项目的基本路径
        String path = BaseServlet.getPath(req, resp);
        System.out.println("path = " + path);
        if ("find.do".equals(path)){
            find(req, resp);
            return;
        }else if ("list.do".equals(path)){
            List<String> foodList = dao.findAddress();
            req.setAttribute("foodList",foodList);
            req.getRequestDispatcher(baseURL+"/pc/food.jsp").forward(req,resp);
        }else if("findAll.do".equals(path)){
            List<Food> foodList = dao.findAll();
            resp.setContentType("application/json;charset=utf-8");
            String json = JSON.toJSONString(foodList);
            PrintWriter out=resp.getWriter();
            out.write(json);
            out.close();
            return;
        }else if ("food-con.do".equals(path)){
            String foodId = req.getParameter("foodId");
            Food food = dao.findById(foodId);
            req.setAttribute("food",food);
            req.getRequestDispatcher(baseURL+"/pc/food-con.jsp").forward(req,resp);
        } else {
            throw new RuntimeException("错误");
        }
    }

    private void find(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String food_name = req.getParameter("food_name");
        String food_sort = req.getParameter("food_sort");
        Map<String,Object> map=new HashMap<String, Object>();
        if (StringUtil.isNotEmpty(food_name)){
            map.put("food_name",food_name);
        }
        if (StringUtil.isNotEmpty(food_sort)){
            map.put("food_sort",food_sort);
        }
        if ("全部菜品".equals(food_sort)){
            map.put("food_sort",null);
        }
        List<Food> foodList = dao.find(map);
        resp.setContentType("application/json;charset=utf-8");
        String json = JSON.toJSONString(foodList);
        PrintWriter out=resp.getWriter();
        out.write(json);
        out.close();
        return;
    }
}
